package com.captain.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * 验证码控制器
 */
@Controller
public class KaptchaController {
    @Autowired
    Producer producer;
    private static final String KAPTCHA_SESSION_KEY="KAPTCHA_SESSION_KEY";

    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletRequest req,HttpServletResponse rep){
        //生成验证码文本
        String codeText=producer.createText();
        //把验证码文本放到session中，用于登录或者注册的时候去验证
        req.getSession().setAttribute(KAPTCHA_SESSION_KEY,codeText);
        //生成验证码图片
        BufferedImage img=producer.createImage(codeText);
        try{
            //设置响应头
            rep.setHeader("Cache-Control", "no-store");
            rep.setContentType("image/jpeg");
            //输出到前台
            ServletOutputStream outputStream = rep.getOutputStream();
            ImageIO.write(img,"jpg",outputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
